package com.example.jimuyutabletcontrol.dialog;


import android.app.Activity;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Bundle;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.DialogFragment;
import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Toast;

import com.example.jimuyutabletcontrol.FileActivity;
import com.example.jimuyutabletcontrol.MapApplication;
import com.example.jimuyutabletcontrol.R;
import com.example.jimuyutabletcontrol.activity.TaskDetailActivity;
import com.example.jimuyutabletcontrol.adapter.taskdialogadapter.TaskDialogAdapter;
import com.example.jimuyutabletcontrol.bean.MakeTaskMapPoint;
import com.example.jimuyutabletcontrol.bean.TaskDialogInfo;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageHandle;
import com.example.jimuyutabletcontrol.network.udp.UdpMessageType;
import com.example.jimuyutabletcontrol.network.udp.UdpSocket;
import com.example.jimuyutabletcontrol.port.TaskFileNameCallback;
import com.example.jimuyutabletcontrol.utils.Constants;
import com.example.jimuyutabletcontrol.utils.TaskUtil;
import com.google.gson.Gson;

import java.io.File;
import java.util.ArrayList;
import java.util.List;

/**
 * A simple {@link Fragment} subclass.
 */
public class TaskDialogFragment extends DialogFragment implements View.OnClickListener {

    private static final String KEY_PARAMS = "key_params_" + TaskDialogFragment.class.getSimpleName();

    private List<File> files;

    private UdpMessageHandle handle;

    public static TaskDialogFragment getInstance(String imei) {
        TaskDialogFragment f = new TaskDialogFragment();
        Bundle params = new Bundle();
        params.putString(KEY_PARAMS, imei);
        f.setArguments(params);
        return f;
    }

    private View rootView;

    private RecyclerView noSendRecyclerView;

    private RecyclerView yetSendRecyclerView;

    private TaskDialogAdapter noSendAdapter;

    private TaskDialogAdapter yetSendAdapter;

    private List<TaskDialogInfo> noSendList;

    private List<TaskDialogInfo> yetSendList;

    private String imei;

    private Context mContext;

    private int noSendClickPosition = -1;

    private int yetSendLastClickPoint = -1;

    private TaskFileNameCallback fileNameCallback;

    private TaskDialogFragment() {
        // Required empty public constructor
    }

    @Override
    public void onAttach(@NonNull Context context) {
        super.onAttach(context);
        this.mContext = context;
    }

    @Override
    public void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        imei = getArguments().getString(KEY_PARAMS);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_task_dialog, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        this.rootView = view;
        initView();
        setAdapter();
        setListeners();
        getData();
    }

    private void getData() {
        getXiaWeiJiTaskData();
        getLocalTaskData();
    }

    public void getXiaWeiJiTaskData() {
        MapApplication.refreshFileDataWithImei(imei, false);
    }

    public void getLocalTaskData() {
        ArrayList<String> list = new ArrayList<>();
        list.add(Constants.TASK_SIGN);
        files = TaskUtil.getFileListData(Constants.FILE_PATH + Constants.TASKMAPFOLDER, list);
        noSendList.clear();
        for (File file : files) {
            TaskDialogInfo info = new TaskDialogInfo();
            info.isSelected = false;
            info.createTime = file.lastModified();
            info.fileName = file.getName();
            noSendList.add(info);
        }
        noSendAdapter.notifyDataSetChanged();
        noSendClickPosition = -1;
    }

    private void setAdapter() {
        noSendList = new ArrayList<>();
        yetSendList = new ArrayList<>();
        noSendAdapter = new TaskDialogAdapter(noSendList);
        yetSendAdapter = new TaskDialogAdapter(yetSendList);
        noSendRecyclerView.setAdapter(noSendAdapter);
        yetSendRecyclerView.setAdapter(yetSendAdapter);
    }

    private void setListeners() {
        rootView.findViewById(R.id.exit).setOnClickListener(this);
        rootView.findViewById(R.id.send).setOnClickListener(this);
//        rootView.findViewById(R.id.delete).setOnClickListener(this);
        rootView.findViewById(R.id.noSendRefresh).setOnClickListener(this);
        rootView.findViewById(R.id.yetSendRefresh).setOnClickListener(this);
        MapApplication.setFileTaskCallback(fileNameCallback = taskFiles -> handelData(taskFiles.get(imei)));
        handle = new UdpMessageHandle(UdpMessageType.TASK_CONTENT, this::receiveAuvTask);
        UdpSocket.getInstance().setMessageCallback(handle);
        noSendAdapter.setOnTaskDialogListener(new TaskDialogAdapter.TaskDialogListener() {
            @Override
            public void onTaskDialogListener(int position) {
                switchNoSend(position);
            }

            @Override
            public void onTaskDialogLongListener(int position) {
                deleteFile(position);
            }

            @Override
            public void onCheckTaskDialogLongListener(int position) {
                TaskDialogInfo info = noSendList.get(position);
                taskDetail(TaskUtil.getTaskUrlWithName(info.fileName));
            }
        });
        yetSendAdapter.setOnTaskDialogListener(new TaskDialogAdapter.TaskDialogListener() {
            @Override
            public void onTaskDialogListener(int position) {
                if (position >= 0 && position < yetSendList.size()) {
                    TaskDialogInfo info = yetSendList.get(position);
                    if (TaskUtil.isHasAuvTaskFileWithName(info.fileName, imei)) {
                        taskDetail(TaskUtil.getAuvTaskUrlWithName(imei, info.fileName));
                    } else {
                        yetSendLastClickPoint = position;
                        UdpSocket.getInstance().sendMessage("B" + imei + "getTaskFileWithName:" + info.fileName);
                    }
                }
            }

            @Override
            public void onTaskDialogLongListener(int position) {
                if (null == yetSendList || position >= yetSendList.size()) return;
                TaskDialogInfo info = yetSendList.get(position);
                if (null == info) return;
                FileDeleteTipDialogFragment fileDeleteTipDialogFragment = new FileDeleteTipDialogFragment();
                fileDeleteTipDialogFragment.setOnFileDeleteTipDialogListener(() -> {
                    UdpSocket.getInstance().sendMessage("B" + imei + "deleteTaskFileName:" + info.fileName);
                    TaskUtil.deleteAuvTaskFileWithName(info.fileName, imei);
                });
                fileDeleteTipDialogFragment.show(getChildFragmentManager(), "deleteFile");
            }

            @Override
            public void onCheckTaskDialogLongListener(int position) {

            }
        });
    }

    private void taskDetail(String url) {
        Intent intent = new Intent();
        intent.setClass(mContext, TaskDetailActivity.class);
        intent.putExtra(TaskDetailActivity.KEY_PARAMS, url);
        startActivity(intent);
    }

    private void receiveAuvTask(String s) {
        ((Activity) mContext).runOnUiThread(() -> {
            String content = s.split("fileName-_-")[1];
            if (content.contains("error-_-")) {
                Toast.makeText(mContext, content.split("error-_-")[1], Toast.LENGTH_SHORT).show();
                return;
            }
            String[] strs = content.split("taskFileContent-_-");
            TaskUtil.saveAuvTask(strs[1], imei, strs[0]);
            if (yetSendLastClickPoint != -1 && yetSendLastClickPoint < yetSendList.size()) {
                TaskDialogInfo info = yetSendList.get(yetSendLastClickPoint);
                if (info.fileName.equals(strs[0])) {
                    info.isDownLoad = true;
                    yetSendAdapter.notifyItemChanged(yetSendLastClickPoint);
                    yetSendLastClickPoint = -1;
                }
            }
        });
    }

    private void handelData(List<String> fileNames) {
        ((Activity) mContext).runOnUiThread(() -> {
            if (fileNames != null) {
                yetSendList.clear();
                for (String name : fileNames) {
                    TaskDialogInfo info = new TaskDialogInfo();
                    info.isSelected = false;
                    info.fileName = name;
                    info.isPad = false;
                    info.isDownLoad = TaskUtil.isHasAuvTaskFileWithName(name, imei);
                    yetSendList.add(info);
                }
                yetSendAdapter.notifyDataSetChanged();
            }
        });
    }

    private void deleteFile(int position) {
        FileDeleteTipDialogFragment fileDeleteTipDialogFragment = new FileDeleteTipDialogFragment();
        fileDeleteTipDialogFragment.setOnFileDeleteTipDialogListener(() -> {
            File file = files.get(position);
            boolean isOk = file.delete();
            if (isOk) {
                files.remove(file);
                noSendList.remove(position);
                noSendAdapter.notifyItemRemoved(position);
                if (position == noSendClickPosition) {
                    noSendClickPosition = -1;
                }
            }
            Toast.makeText(mContext, isOk ? "删除成功" : "删除失败", Toast.LENGTH_SHORT).show();
        });
        fileDeleteTipDialogFragment.show(getChildFragmentManager(), "fileDeleteTipDialogFragment");
    }

    private synchronized void switchNoSend(int position) {
        if (noSendClickPosition != position) {
            TaskDialogInfo noSendInfo = noSendList.get(position);
            noSendInfo.isSelected = !noSendInfo.isSelected;
            noSendAdapter.notifyItemChanged(position);
            if (noSendClickPosition != -1) {
                TaskDialogInfo noSendInfoLast = noSendList.get(noSendClickPosition);
                noSendInfoLast.isSelected = !noSendInfoLast.isSelected;
                noSendAdapter.notifyItemChanged(noSendClickPosition);
            }
            noSendClickPosition = position;
        }
    }

    private void initView() {
        noSendRecyclerView = rootView.findViewById(R.id.noSendRecyclerView);
        yetSendRecyclerView = rootView.findViewById(R.id.yetSendRecyclerView);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.send:
                if (noSendClickPosition != -1 && noSendClickPosition < noSendList.size()) {
                    if (hasYetSend(noSendClickPosition)) {
                        Toast.makeText(mContext, "已经发送此文件", Toast.LENGTH_SHORT).show();
                        return;
                    }
                    List<MakeTaskMapPoint.PackageAuxiliaryPoint> list = TaskUtil.getTaskWithTaskFile(files.get(noSendClickPosition).getAbsolutePath());
                    TaskDialogInfo info = noSendList.get(noSendClickPosition);
                    String senddata = "TASKINFO:" + imei + "-" + info.fileName + "-" + info.createTime + "___" + new Gson().toJson(list);
                    UdpSocket.getInstance().sendMessage(senddata);
                } else Toast.makeText(mContext, "请选中需要发送的一项数据", Toast.LENGTH_SHORT).show();
                break;
            case R.id.exit:
                dismiss();
                break;
            case R.id.noSendRefresh:
                getLocalTaskData();
                break;
            case R.id.yetSendRefresh:
                getXiaWeiJiTaskData();
                break;
        }
    }

    public boolean hasYetSend(int position) {
        if (position >= noSendList.size()) return true;
        TaskDialogInfo info = noSendList.get(position);
        for (TaskDialogInfo yetSendInfo : yetSendList) {
            if (yetSendInfo.fileName.equals(info.fileName)) {
                return true;
            }
        }
        return false;
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        MapApplication.removeFileTaskCallback(fileNameCallback);
        fileNameCallback = null;
        if (null != handle) {
            UdpSocket.getInstance().removeMessageCallback(handle);
            handle = null;
        }
    }
}
